package com.liuh.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

/**
 * @note 根据action标示执行servlet中的method
 * @author liuh
 * @date 2021年5月31日 上午10:44:08
 */
public class AdvanceServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action=req.getParameter("action");
		if(StrUtil.isBlank(action)) {
			//404
			toView("/404.jsp", req, resp);
		}else {
			Method method = ReflectUtil.getMethod(this.getClass(), action, HttpServletRequest.class, HttpServletResponse.class);
			if(method==null) {
				//404
				toView("/404.jsp", req, resp);
			}else {
				Object result= ReflectUtil.invoke(this, method, req, resp);
				toView(result, req, resp);
			}
		}
	}

	//过滤器已设置post编码方式
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
	
	/**
	 * @note 根据方法返回值验证是渲染页面还是json数据
	 * 渲染页面有2中方式，转发 or 重定向 (返回值加前缀---redirect:)
	 * @author liuh
	 * @date 2021年5月31日 上午11:30:20
	 */
	protected void toView(Object result, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		if(result!=null) {
			if(result instanceof String) {
				//to jsp view
				resp.setContentType("text/html;charset=UTF-8");
				String viewName = result.toString();
				String viewName1 = viewName.substring(viewName.lastIndexOf(":")+1);
				if(viewName.startsWith("redirect:")) {
					//重定向
					resp.sendRedirect(viewName1);
				}else {
					//转发
			        req.getRequestDispatcher(viewName1).forward(req, resp);
				}
			}else {
				//to Json data
				resp.setContentType("application/json;charset=utf-8");
				outReps(JSONUtil.toJsonStr(result), resp);
			}
		}
	}
	
	protected void outReps(String msg, HttpServletResponse resp) throws IOException {
		PrintWriter out = resp.getWriter();
		out.print(msg);
		out.flush();
		out.close();
	}
	
	protected String msgAlert(String msg, String url) {
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append("<script type=\"text/javascript\">");
        sbBuffer.append("alert(\"" + msg + "\");");
        sbBuffer.append("open(\"" + url + "\", \"_self\"); ");
        sbBuffer.append("</script>");
        return sbBuffer.toString();
    }

}
